package com.ztm.shortlink.admin.config;

import cn.hutool.jwt.JWTUtil;
import com.ztm.shortlink.admin.common.context.BaseContext;
import com.ztm.shortlink.admin.common.convention.exception.ClientException;
import com.ztm.shortlink.admin.common.properties.JwtProperties;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
@RequiredArgsConstructor
public class JwtInterceptor implements HandlerInterceptor {

    private final JwtProperties jwtProperties;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getTokenName());

        //2、校验令牌
        log.info("jwt校验:{}", token);
        try{
            boolean verify = JWTUtil.verify(token, jwtProperties.getSecretKey().getBytes());
            if(!verify){
                throw new Exception();
            }
            String username = (String) JWTUtil.parseToken(token).getPayload("username");
            log.info("当前用户username：{}", username);
            BaseContext.setCurrentUsername(username);
            return true;
        }catch (Exception ex){
            throw new ClientException("用户未登录");
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentUsername();
    }
}
